package com.lagou.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     *
     * @param path 静态资源相对路径
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态资源文件输入流，通过socket输出流输出
     *
     * @param inputStream  文件输入流
     * @param outputStream socket输出流
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        //文件总大小
        int resourceSize = inputStream.available();

//        byte[] bytes = new byte[resourceSize];
//        inputStream.read(bytes);
//        System.out.println(new String(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes()) + new String(bytes));

        /**
         * 输出响应头
         */
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        /**
         * 输入响应体
         */
        //已输出大小
        long written = 0;
        //缓冲池
        byte[] bytes;
        //缓冲池大小
        int byteSize = 1024;
        while (written < resourceSize) {
            //剩余大小不足1024字节
            int remaining = (int) (resourceSize - written);
            if (remaining > byteSize) {
                byteSize = remaining;
            }
            bytes = new byte[byteSize];
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }

}
